// pages/register/register.js
Page({
  data: {
    phone: '',
    password: '',
    confirmPassword: '',
    nickname: '', // 昵称字段
    isAgreed: false,
    canRegister: false, // 是否可注册
    registerText: '注册'
  },

  onLoad() {
    // 页面加载逻辑
  },

  // 手机号输入
  onPhoneInput(e) {
    const phone = e.detail.value;
    this.setData({ phone });
    this.checkCanRegister();
  },

  // 密码输入
  onPasswordInput(e) {
    const password = e.detail.value;
    this.setData({ password });
    this.checkCanRegister();
  },

  // 确认密码输入
  onConfirmPasswordInput(e) {
    const confirmPassword = e.detail.value;
    this.setData({ confirmPassword });
    this.checkCanRegister();
  },

  // 昵称输入
  onNicknameInput(e) {
    this.setData({ 
      nickname: e.detail.value.trim() 
    });
    this.checkCanRegister();
  },

  // 注册（核心逻辑）
  onRegister() {
    if (!this.data.canRegister) return;

    if (!this.data.isAgreed) {
      wx.showToast({
        title: '请先同意用户协议和隐私政策',
        icon: 'none'
      });
      return;
    }

    if (this.data.password !== this.data.confirmPassword) {
      wx.showToast({
        title: '两次输入的密码不一致',
        icon: 'none'
      });
      return;
    }

    this.setData({ registerText: '注册中...' });

    // 调用注册接口（无验证码）
    wx.request({
      url: 'http://localhost/dev-api/userr/users', 
      method: 'POST',
   
      data: {
        phone: this.data.phone,
        password: this.data.password,
        nickname: this.data.nickname,
        // 可选字段（按接口要求传递）
        avatarUrl: null,
        sex: null,
        birthday: null,
        address: null,
        status: 0
      },
      success: (res) => {
        console.log('注册响应：', res);
        const result = res.data;

        // 按后端实际成功标识判断（示例：code=200为成功）
        if (result.code === 200) {
          wx.showToast({ title: '注册成功', icon: 'success' });
          
          // 保存用户信息
          wx.setStorageSync('userInfo', {
            id: result.data?.id,
            nickname: result.data?.nickname,
            phone: result.data?.phone,
            joinTime: result.data?.joinTime,
            totalPoint: result.data?.totalPoint,
            isVip: result.data?.isVip
          });

          // 跳转主页
          // setTimeout(() => {
          //   wx.switchTab({ url: '/pages/index/index' });
          // }, 1500);
          setTimeout(() => {
            wx.navigateTo({ url: '/pages/recommend/recommend' });
          }, 1500);
        } else {
          wx.showToast({
            title: result.msg || '注册失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({ title: '网络异常，请稍后重试', icon: 'none' });
        console.error('注册失败：', err);
      },
      complete: () => {
        this.setData({ registerText: '注册' });
      }
    });
  },

  // 微信注册
  onWechatRegister() {
    wx.showLoading({ title: '注册中...' });

    setTimeout(() => {
      wx.hideLoading();
      
      const userInfo = {
        id: null,
        nickname: '微信用户',
        avatarUrl: 'https://picsum.photos/120/120?random=888',
        phone: '',
        sex: null,
        birthday: null,
        joinTime: new Date().toISOString().split('T')[0],
        status: 0,
        totalPoint: '0',
        isVip: 0
      };

      wx.setStorageSync('userInfo', userInfo);
      wx.setStorageSync('token', 'wechat_token_' + Date.now());

      wx.showToast({ title: '注册成功', icon: 'success' });
       setTimeout(() => {
         wx.switchTab({ url: '/pages/index/index' });
       }, 1500);
      // 注册成功后跳转至推荐页面
// setTimeout(() => {
//   wx.navigateTo({ url: '/pages/recommend/recommend' });
// }, 1500);
   }, 1500);
  },


  // 协议同意状态切换
  onToggleAgreement() {
    this.setData({ isAgreed: !this.data.isAgreed });
  },

  // 跳转协议页面
  onUserAgreement() {
    wx.navigateTo({ url: '/user/pages/user-agreement/user-agreement' });
  },
  onPrivacyPolicy() {
    wx.navigateTo({ url: '/user/pages/privacy-policy/privacy-policy' });
  },

  // 去登录
  onGoLogin() {
    wx.navigateBack();
  },

  // 手机号验证
  validatePhone(phone) {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  },

  // 检查是否可注册（无验证码校验）
  checkCanRegister() {
    const { phone, password, confirmPassword, nickname } = this.data;
    
    // 校验条件：手机号有效 + 密码≥6位 + 两次密码一致 + 昵称不为空
    const canRegister = this.validatePhone(phone) && 
                       password.length >= 6 && 
                       password === confirmPassword && 
                       nickname.trim().length > 0;
    this.setData({ canRegister });
  }
});